package com.cdn.clock.component.rate;

import com.cdn.clock.component.IRateComponent;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * 蔡定努
 * 2024/06/05 22:45
 */
@ConditionalOnProperty(prefix = "clock", name = "rate-limit-type", havingValue = "redission", matchIfMissing = true)
public class RedissionRateComponent implements IRateComponent {

    private static final Log log = LogFactory.getLog(RedissionRateComponent.class);

    @Autowired
    private RedissonClient redissonClient;

    public RedissionRateComponent() {
        log.info("RedissionRateComponent init……………………");
    }

    /**
     * @author 蔡定努
     */
    @Override
    public boolean rateLimit(String key, long count, long rateInterval,TimeUnit timeUnit) {
        RRateLimiter limiter = redissonClient.getRateLimiter(key);
        long millis = timeUnit.toMillis(rateInterval);
        limiter.trySetRate(RateType.OVERALL, count, millis, RateIntervalUnit.MILLISECONDS);
        limiter.expire(Duration.ofMillis(millis));
        return limiter.tryAcquire(1);
    }

}
